package com.wlz.client;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

/**
 * @author wlz
 * @date 2022-06-25  8:04 下午
 */
@Slf4j
public class BaseOperationsClient extends StandaloneBase{

    private String first_node = "/first_node";

    /**
     *  创建节点 持久节点
     * @throws Exception
     */
    @Test
    public void testCreate() throws Exception{
        ZooKeeper zooKeeper = getZooKeeper();

        String s = zooKeeper.create(first_node, "first_node_data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        log.info("create: {}", s);
    }

    /**
     *  获取 节点并 进行 循环监听
     */
    @Test
    public void testGetData() throws Exception{

        Watcher watcher = new Watcher() {
            @SneakyThrows
            @Override
            public void process(WatchedEvent event) {
                if (event.getPath() != null && event.getPath().equals(first_node)
                && event.getType() == Event.EventType.NodeDataChanged) {
                    log.info(" path: {} 发生变化", first_node);

                    // 进行监听
                    byte[] data = getZooKeeper().getData(first_node, this, null);
                    log.info("data: {}", new String(data));
                }
            }
        };

        byte[] data = getZooKeeper().getData(first_node, watcher, null);
        log.info("data: {} ", new String(data));
    }

    /**
     *  修改 节点数据
     */
    @Test
    public void testSetData() throws Exception {

        ZooKeeper zooKeeper = getZooKeeper();

        Stat stat = new Stat();
        byte[] data = zooKeeper.getData(first_node, false, stat);
        log.info("data: {} 修改前数据", new String(data));

        Stat stat1 = zooKeeper.setData(first_node, "third".getBytes(), 0);
        log.info(" set data version : {} 修改后状态", stat1.getAversion());
    }

    @Test
    public void testDelete() throws Exception{
        // -1 代表 匹配所有版本，直接删除
        // 任意大于 -1 的代表可以指定数据版本删除
        getZooKeeper().delete(first_node, -1);
        log.info("node: {} 删除", first_node);
    }

    @Test
    public void asyncTest() throws Exception{
        String userId = "xxxxx";
        getZooKeeper().getData(first_node, false, (rc, path, ctx, data, stat) -> {
            Thread thread = Thread.currentThread();
            log.info(" thread name: {}, rc: {}, path: {}, ctx:{}, data:{}, stat: {}", thread.getName(), rc, path, ctx,new String(data),stat);
        },"test");
        log.info("over .....");
    }

}
